package com.zy.handler;

import com.zy.annon.ZySpi;
import com.zy.driver.ZyDbDriver;
import com.zy.driver.impl.DefaultZyDbDriver;

import java.util.ServiceLoader;

/**
 * @author hugx
 * @create 2018-07-04 16:23
 */

public class ZyDbDriverHandlerTools {

    private static ZyDbDriverHandlerTools instance;

    private ZyDbDriver zyDbDriver;
    private String zyDbDriverName;

    private ZyDbDriverHandlerTools(String zyDbDriverName) {
        this.zyDbDriverName = zyDbDriverName;
        init();
    }

    public static synchronized ZyDbDriverHandlerTools getInstance(String zyDbDriverName) {
        if (instance == null) {
            instance = new ZyDbDriverHandlerTools(zyDbDriverName);
        }

        return instance;
    }

    public ZyDbDriver getZyDbDriver() {
        return zyDbDriver;
    }


    public void refash(String zyDbDriverName) {
        this.zyDbDriverName = zyDbDriverName;
        init();
    }

    private void init() {
        System.out.println("-----call init()  of  ZyDbDriverHandlerTools");
        ServiceLoader<ZyDbDriver> serviceLoader = ServiceLoader.load(ZyDbDriver.class);
        if (serviceLoader == null || serviceLoader.iterator() == null) {
            return;
        }

        boolean flag = false;
        for (ZyDbDriver zyDbDriver : serviceLoader) {
            if (zyDbDriver == null) {
                continue;
            }

            String zySpiVal = getZySpiVal(zyDbDriver.getClass());
            if (zySpiVal != null && zySpiVal.length() > 0 && zySpiVal.equals(zyDbDriverName)) {
                System.out.println("-----call init()  of  ZyDbDriverHandlerTools  实例化 zyDbDriver Ok type: "+zySpiVal);
                this.zyDbDriver = zyDbDriver;
                flag = true;
                break;
            }
        }

        if (!flag) {
            System.out.println("-----call init()  of  ZyDbDriverHandlerTools  实例化 zyDbDriver Ok type: default");
            this.zyDbDriver = new DefaultZyDbDriver();
        }
    }

    private String getZySpiVal(Class type) {
        String result = null;
        final ZySpi defaultAnnotation = (ZySpi) type.getAnnotation(ZySpi.class);
        if (defaultAnnotation != null) {
            result = defaultAnnotation.value();
        }

        return result;
    }
}
